﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Collections;
using System.IO;

//---------------------------------------------------------------------------------//

//--------------------------------新事务的产生与处理算法-----------------------------//

//---------------------------------------------------------------------------------//


namespace LJTest
{
    class Transaction
    {
        public static bool isGetPackage = false;
        public static string dataPackage = "";
        public static int lineNum = 0; //排队等待执行的事务个数
        public static Queue transactionQueue = new Queue(); //排队等待执行的事务队列

        //public static ArrayList incache ;
        //public static ArrayList notincache;

        public static void AddTransaction(ArrayList tran)
        {
            
                //从队列一端插入内容 
                transactionQueue.Enqueue(tran);
                Console.WriteLine("成功插入一条待处理事务:" + Common.arraylistTostring(tran));
           
        } 
        public static ArrayList createTransaction(int width, int seed)
        {
            //在此产生一条事务项。。。
            ArrayList array = new ArrayList();
            string str;
            Random random = new Random();
            ZipfSelect zipf = new ZipfSelect(seed, 1.0);
            ZipfSelect.SetRandomSeed(DateTime.Now.Second);
            //ZipfSelect.SetRandomSeed(100);

            str = "\n" + DateTime.Now.ToString() + "|" + (Form1.currentLineNum) + ",";
            for (int x = 0; x < width; x++)
            {
                string temp = zipf.Pick().ToString();//random.Next(100);
                str += (x == width - 1 ? temp : (temp + ","));
                array.Add(temp);

            }

            //str += "\n";
            //write to transaction_temp:
            StreamWriter transtreamwriter = new StreamWriter(Common.TRANSACTION_FILE_TEMP, true);
            transtreamwriter.WriteLine(str);
            transtreamwriter.Close();
            //write to transaction:
            transtreamwriter = new StreamWriter(Common.TRANSACTION_FILE_PATH, true);
            transtreamwriter.WriteLine(str);
            transtreamwriter.Close();

            return array;
        }
        /* **
         * 处理一条事务中的有效和失效数据，写入数据库LOG
         * array:生成的一条事务
         * 
         ** */
        public static void  processTransaction()
        {
            Console.WriteLine("处理本阶段事务开始");
            //if (lineNum == 0)
            //{
            //    isGetPackage = false;
            //    dataPackage = "";
            //}
            //else
            //{
            //    lineNum--;
            //}
            //是否在缓存中
            //isGetPackage = false;
            //dataPackage = "";
            //lock (transactionQueue)
            //{
            while(transactionQueue.Count >0)
            {
                ArrayList array = (ArrayList)transactionQueue.Dequeue();
                int cachenum = 0;
                ArrayList incache = new ArrayList();
                ArrayList notincache = new ArrayList();
                ArrayList cacheData = Common.readCacheDataFromDB(Common.CACHE_TABLE); //Common.getCache(Common.CACHE_FILE);
                ArrayList cacheTempData = Common.readCacheDataFromDB(Common.CACHE_TEMP_TABLE); //Common.getCache(Common.CACHE_TEMP_FILE);

                foreach (string o in array)
                {
                    if (cacheData.Contains(o) || cacheTempData.Contains(o))
                    {
                        //是否是最新的
                        incache.Add(o);

                    }

                    else
                    {
                        notincache.Add(o);

                    }
                }
                ArrayList incacheClone = (ArrayList)incache.Clone();
                //while (true)
                //{      //等待服务器传来更新数据包
                //    if (isGetPackage)
                //    {
                        ArrayList package = new ArrayList();
                        foreach (string k in dataPackage.Split(','))
                        {
                            package.Add(k);
                        }

                        foreach (string k in incache)
                        {
                            if (package.Contains(k))
                            {
                                notincache.Add(k); //不在缓存中的项
                                incacheClone.Remove(k);
                            }
                            else
                            {
                                cachenum++; //命中数
                            }
                        }
                        //isGetPackage = false;
                        //dataPackage = "";
                        //break;
                //    }

                //}

                string notincacheStr = "";
                string incacheStr = "";
                string arrayStr = "";
                int index = 0;
                foreach (string str in notincache)  //不在缓存中的项
                {
                    if (index == notincache.Count - 1)
                    {
                        notincacheStr += str;
                    }
                    else
                    {
                        notincacheStr += str + ",";
                        index++;
                    }
                }
                index = 0;
                foreach (string str in incacheClone) //在缓存中的项
                {
                    if (index == incacheClone.Count - 1)
                    {
                        incacheStr += str;
                    }
                    else
                    {
                        incacheStr += str + ",";
                        index++;
                    }
                }
                index = 0;
                foreach (string str in array) //整个事务
                {
                    if (index == array.Count - 1)
                    {
                        arrayStr += str;
                    }
                    else
                    {
                        arrayStr += str + ",";
                        index++;
                    }
                }


                string sql = "insert into log(addtime,transactions,totalnum,incachenum,incache,notincache) values('" + DateTime.Now.ToString("s") + "' ,'" + arrayStr + "','" + array.Count + "','" + cachenum + "','" + incacheStr + "','" + notincacheStr + "')";
                SQLiteHelper.ExecuteSql(sql);

                //事务中某个数据项失效时获得的预取集合
                invalidprefetch.invalidpre(notincache);
            }
            Console.WriteLine("处理本阶段事务结束");
        }

        public static int getRequestData(int x)
        {
            //...
            return 0;
        }



        internal static void updateCache(int requestData)
        {
            throw new NotImplementedException();
        }

        public static ArrayList getTransactions(string transationFileName)
        {
            ArrayList Lc=new ArrayList ();
            if (File.Exists(transationFileName))
            {
                //Console.WriteLine("文件查找成功");
                try
                {
                    String InLine;

                    ArrayList Lsub = new ArrayList();
                    using (StreamReader sr = new StreamReader(transationFileName, Encoding.GetEncoding("gb2312")))
                    {


                        while ((InLine = sr.ReadLine()) != null)
                        {
                            foreach (string k in InLine.Split(','))
                            {
                                Lsub.Add(k);
                            }
                            Lc.Add(Lsub);
                            Lsub = new ArrayList();
                        }

                    }
                }
                catch (Exception ex)
                {

                }
            }
            return Lc;
        }
    }
}
